/*
 *	Filename: Quadrotor_ePwm.c
 *	Fuction: Configure ePwm Module to Drive Motors
 *	Modified: 2016-11-09
 *	Author: Bin
 */

#include "DSP28x_Project.h"
#include "Quadrotor_ePwm.h"

void InitEPwmGpioAll(void) {
	// ePwm1 and ePwm2 are Used	
	InitEPwm1Gpio();
	InitEPwm2Gpio();	
}

void InitEPwmAll(void) {
	// ePwm1 and ePwm2 are Used
	EALLOW;
	SysCtrlRegs.PCLKCR0.bit.TBCLKSYNC = 0;
	EDIS;

	InitEPwmx(&EPwm1Regs);
	InitEPwmx(&EPwm2Regs);

	EALLOW;
	SysCtrlRegs.PCLKCR0.bit.TBCLKSYNC = 1;
	EDIS;
}

void setEPwm1A(Uint16 value) {
	value = (float32)value * 1.5625f;
	EPwm1Regs.CMPA.half.CMPA = value % 3125;
}

void setEPwm1B(Uint16 value) {
	value = (float32)value * 1.5625f;
	EPwm1Regs.CMPB = value % 3125;
}

void setEPwm2A(Uint16 value) {
	value = (float32)value * 1.5625f;
	EPwm2Regs.CMPA.half.CMPA = value % 3125;
}

void setEPwm2B(Uint16 value) {
	value = (float32)value * 1.5625f;
	EPwm2Regs.CMPB = value % 3125;
}

void InitEPwm1Gpio(void) {

	EALLOW;

	GpioCtrlRegs.GPAPUD.bit.GPIO0 = 0;	// Enable pull-up on GPIO0 (EPWM1A)
	GpioCtrlRegs.GPAPUD.bit.GPIO1 = 0;	// Enable pull-up on GPIO1 (EPWM1B)

	GpioCtrlRegs.GPAMUX1.bit.GPIO0 = 1;	// Configure GPIO0 as EPWM1A
	GpioCtrlRegs.GPAMUX1.bit.GPIO1 = 1;	// Configure GPIO1 as EPWM1B

	EDIS;
}

void InitEPwm2Gpio(void) {

	EALLOW;

	GpioCtrlRegs.GPAPUD.bit.GPIO2 = 0;	// Enable pull-up on GPIO2 (EPWM2A)
    GpioCtrlRegs.GPAPUD.bit.GPIO3 = 0;	// Enable pull-up on GPIO3 (EPWM3B)

    GpioCtrlRegs.GPAMUX1.bit.GPIO2 = 1;	// Configure GPIO2 as EPWM2A
    GpioCtrlRegs.GPAMUX1.bit.GPIO3 = 1;	// Configure GPIO3 as EPWM2B

	EDIS;
}

void InitEPwmx(volatile struct EPWM_REGS *regAddr) {
	// Most Precompiled Definition Found in DSP2833x_ePwm_defines.h
	//SET TB Module
	regAddr->TBCTL.bit.CTRMODE = TB_COUNT_UP;
	regAddr->TBPRD = EPWM_TIMER_TBPRD;		// Quadrotor_ePwm.h
	regAddr->TBCTL.bit.PRDLD = TB_SHADOW;
	regAddr->TBCTL.bit.PHSEN = TB_DISABLE;
	regAddr->TBPHS.half.TBPHS = 0x0000;
	regAddr->TBCTR = 0x0000;
	regAddr->TBCTL.bit.HSPCLKDIV = HSPCLK_DIV12;	// Quadrotor_ePwm.h
	regAddr->TBCTL.bit.CLKDIV = CLK_DIV8;		// Quadrotor_ePwm.h

	//SET CMP Module
	regAddr->CMPCTL.bit.SHDWAMODE = CC_IMMEDIATE;
	regAddr->CMPCTL.bit.SHDWBMODE = CC_IMMEDIATE;
	// regAddr->CMPCTL.bit.LOADAMODE = CC_CTR_ZERO;
	// regAddr->CMPCTL.bit.LOADBMODE = CC_CTR_ZERO;

	regAddr->CMPA.half.CMPA = EPWM_INIT_CMPA;	// Quadrotor_ePwm.h
	regAddr->CMPB = EPWM_INIT_CMPB;			// Quadrotor_ePwm.h

	//SET AQ Module
	regAddr->AQCTLA.bit.ZRO = AQ_SET;
	regAddr->AQCTLA.bit.CAU = AQ_CLEAR;

	regAddr->AQCTLB.bit.ZRO = AQ_SET;
	regAddr->AQCTLB.bit.CBU = AQ_CLEAR;
}
